package com.heima.consumer.web.controller;

import com.heima.cloud.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    public RestTemplate restTemplate;

    @Autowired
    public DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallBack")
    public User queryById(@PathVariable("id") String username){
//        String url="http://localhost:8081/user/"+username;
//        Map userMapper = restTemplate.getForObject(url, Map.class);

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance instance = instances.get(0);
//        String host = instance.getHost();
//        int port = instance.getPort();
//        String url = instance.getUri().toString();
//
//        System.out.println("url = " + url);
//        System.out.println("host = " + host);
//        System.out.println("port = " + port);
//        Map userMapper = restTemplate.getForObject(url+"/user/"+username, Map.class);



        String url="http://user-service/user/"+username;

        if ("itheima".equals(username)) {
            throw new RuntimeException("itheima");
        }
        User user = restTemplate.getForObject(url, User.class);


        return user;
    }

    public User queryByIdFallBack(String username){
        User user=new User();
        user.setName("服务暂停"+username);
        return user;
    }
}
